<!--
 * @Author: your name
 * @Date: 2021-07-05 11:36:39
 * @LastEditTime: 2023-03-27 15:13:31
 * @LastEditors: Will
 * @Description: In User Settings Edit
 * @FilePath: \cloud-space\components\nfcModule\nfcModule.vue
  NFC识别组件
-->

<template>
  <div class="nfcModule"></div>
</template>

<script>
export default {
  name: "nfcModule",
  components: {},
  data() {
    return {
      info: {},
      taskNums: {},
      taskData: [],
      id: "",
      NFC: null,
      NfcAdapter: null,
      NdefRecord: null,
      NdefMessage: null,
      readyWriteData: false,
      readyRead: false,
      noNFC: false,
      techListsArray: [
        ["android.nfc.tech.IsoDep"],
        ["android.nfc.tech.NfcA"],
        ["android.nfc.tech.NfcB"],
        ["android.nfc.tech.NfcF"],
        ["android.nfc.tech.Nfcf"],
        ["android.nfc.tech.NfcV"],
        ["android.nfc.tech.NdefFormatable"],
        ["android.nfc.tech.MifareClassi"],
        ["android.nfc.tech.MifareUltralight"],
      ],
      cardId: "",
      package_TECH_DISCOVERED: "android.nfc.action.TECH_DISCOVERED",
    };
  },
  created() {
    this.initNFC();
    // let msg = `{"ctype":"4011","data":{"id":"${this.id}"}}`;
    // uni.sendSocketMessage({
    //   data: msg,
    // });
  },
  onShow() {
    // 4011  3维场景 切换到 点检页面
    // 4012  点击把数据发送到3维场景
    // 4013  扫描NFC 发送数据到3维场景
  },
  onReady() {},
  methods: {
    // init NFC
    initNFC() {
      //#ifdef APP-PLUS
      console.log("init NFC");
      let that = this;
      if (that.NFC == null) {
        try {
          that.readyRead = true;
          that.NFC = plus.android.runtimeMainActivity();
          let Intent = plus.android.importClass("android.content.Intent");
          let Activity = plus.android.importClass("android.app.Activity");
          let PendingIntent = plus.android.importClass(
            "android.app.PendingIntent"
          );
          let IntentFilter = plus.android.importClass(
            "android.content.IntentFilter"
          );
          that.NfcAdapter = plus.android.importClass("android.nfc.NfcAdapter");
          let nfcAdapter = that.NfcAdapter.getDefaultAdapter(that.NFC);

          if (nfcAdapter == null) {
            uni.showToast({
              title: "设备不支持NFC！",
              icon: "none",
            });
            that.noNFC = true;
            return;
          }
          if (!nfcAdapter.isEnabled()) {
            uni.showToast({
              title: "请在系统设置中先启用NFC功能！",
              icon: "none",
            });
            that.noNFC = true;

            setTimeout(() => {
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
            return;
          } else {
            that.noNFC = false;
          }

          let intent = new Intent(that.NFC, that.NFC.getClass());
          intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
          let pendingIntent = PendingIntent.getActivity(that.NFC, 0, intent, 0);
          let ndef = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
          ndef.addDataType("*/*");
          let intentFiltersArray = [ndef];

          plus.globalEvent.addEventListener("newintent", function () {
            console.log("newintent running");
            // 轮询调用 NFC
            that.nfcRuning();
          });
          plus.globalEvent.addEventListener("pause", function (e) {
            console.log("pause running");
            if (nfcAdapter) {
              //关闭前台调度系统
              //恢复默认状态
              nfcAdapter.disableForegroundDispatch(that.NFC);
            }
          });
          plus.globalEvent.addEventListener("resume", function (e) {
            console.log("resume running");
            if (nfcAdapter) {
              //开启前台调度系统
              // 优于所有其他NFC
              nfcAdapter.enableForegroundDispatch(
                that.NFC,
                pendingIntent,
                intentFiltersArray,
                that.techListsArray
              );
            }
          });
          nfcAdapter.enableForegroundDispatch(
            that.NFC,
            pendingIntent,
            intentFiltersArray,
            that.techListsArray
          );
        } catch (e) {
          console.error(e);
        }
      }

      //#endif
    },
    nfcRuning() {
      //#ifdef APP-PLUS
      let that = this;
      that.NdefRecord = plus.android.importClass("android.nfc.NdefRecord");
      that.NdefMessage = plus.android.importClass("android.nfc.NdefMessage");
      that.NFC = plus.android.runtimeMainActivity();
      let intent = that.NFC.getIntent();

      console.log("action type:" + intent.getAction());

      if (that.package_TECH_DISCOVERED == intent.getAction()) {
        if (that.readyWriteData) {
          that.write(intent);
          that.readyWriteData = false;
        } else if (that.readyRead) {
          that.read(intent);
          // that.readyRead = false;
        }
      }
      //#endif
    },
    write(intent) {
      //#ifdef APP-PLUS
      try {
        this.$util.tip("请勿移开标签 正在写入...");
        console.log("text=" + text);

        let textBytes = plus.android.invoke(text, "getBytes");
        // image/jpeg text/plain
        let textRecord = new NdefRecord(
          NdefRecord.TNF_MIME_MEDIA,
          plus.android.invoke("text/plain", "getBytes"),
          plus.android.invoke("", "getBytes"),
          textBytes
        );
        let message = new NdefMessage([textRecord]);
        let Ndef = plus.android.importClass("android.nfc.tech.Ndef");
        let NdefFormatable = plus.android.importClass(
          "android.nfc.tech.NdefFormatable"
        );
        let tag = intent.getParcelableExtra(that.NfcAdapter.EXTRA_TAG);
        let ndef = Ndef.get(tag);
        if (ndef != null) {
          // 待写入的数据长度
          let size = message.toByteArray().length;
          ndef.connect();
          if (!ndef.isWritable()) {
            this.$util.tip("tag不允许写入！");
            return;
          }
          if (ndef.getMaxSize() < size) {
            this.$util.tip("文件大小超出容量！");
            return;
          }
          ndef.writeNdefMessage(message);
          this.$util.tip("写入数据成功！");
          return;
        } else {
          let format = NdefFormatable.get(tag);
          if (format != null) {
            try {
              format.connect();
              format.format(message);
              this.$util.tip("格式化tag并且写入message");
              return;
            } catch (e) {
              this.$util.tip("格式化tag失败.");
              return;
            }
          } else {
            this.$util.tip("Tag不支持NDEF");
            return;
          }
        }
      } catch (e) {
        this.$util.tip("写入失败");
        console.log("error=" + e);
      }
      //#endif
    },
    read(intent) {
      //#ifdef APP-PLUS
      // console.log(intent);
      let that = this;
      // this.$util.tip("请勿移开标签正在读取数据");
      // NFC id
      // return
      let bytesId = intent.getByteArrayExtra(that.NfcAdapter.EXTRA_ID);
      let nfc_id = that.byteArrayToHexString(bytesId);
      // console.log('nfc_id:', nfc_id);
      let Parcelable = plus.android.importClass("android.os.Parcelable");
      let rawmsgs = intent.getParcelableArrayExtra(
        "android.nfc.extra.NDEF_MESSAGES"
      );
      //let rawmsgs = intent.getParcelableArrayExtra();

      if (rawmsgs != null && rawmsgs.length > 0) {
        let records = rawmsgs[0].getRecords();
        let result = records[0].getPayload();
        
        let codeId = plus.android.newObject("java.lang.String", result.slice(3));

        console.log("NFC 数据：", codeId, "NFCID:", nfc_id);

        this.$emit("nfcData", { codeId: codeId, nfc_id: nfc_id });
      } else {
        this.$util.tip("没有读取到数据");
      }
      //#endif
    },
    byteArrayToHexString: function (inarray) {
      // converts byte arrays to string
      let i, j, inn;
      let hex = [
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
      ];
      let out = "";

      for (j = 0; j < inarray.length; ++j) {
        inn = inarray[j] & 0xff;
        i = (inn >>> 4) & 0x0f;
        out += hex[i];
        i = inn & 0x0f;
        out += hex[i];
      }
      return out;
    },
    writeData() {
      if (this.noNFC) {
        this.$util.tip("请检查设备是否支持并开启 NFC 功能！");
        return;
      }
      // 轮询条件
      this.readyWriteData = true;
      this.$util.tip("请将NFC标签靠近！");
    },
    readData() {
      if (this.noNFC) {
        this.$util.tip("请检查设备是否支持并开启 NFC 功能！");
        return;
      }
      // 轮询条件
      this.readyRead = true;
      this.$util.tip("请将NFC标签靠近！");
    },
  },
  onHide() {
    // console.log(333);
    // this.nfcRuning();
  },
  destroyed() {
    //#ifdef APP-PLUS
    // plus.android.autoCollection(this.NFC)
    this.$store.state.spotNfcId = 0;
    this.NFC = null;
    this.readyRead = false;
    plus.globalEvent.removeEventListener("newintent", function () {
      console.log("newintent");
    });
    plus.globalEvent.removeEventListener("pause", function () {
      console.log("pause");
    });
    plus.globalEvent.removeEventListener("resume", function () {
      console.log("resume");
    });
    //#endif
  },
  onUnload() {
    // console.log(123);
  },
};
</script>

<style lang="less" scoped>
.spotCheckTask {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  background-color: #f5f5f5;
  position: relative;
}
.scroll {
  width: 100%;
  height: 100%;
}
/deep/ .uni-scroll-view-content {
  flex-direction: column;
}
.form-module {
  bottom: 112upx;
}
.manger {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  position: relative;
  .info {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
  .head {
    width: 85upx;
    height: 85upx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 20upx;
  }
  .name {
    font-size: 33upx;
    color: #1d256e;
    margin-bottom: 5upx;
  }
  .code {
    font-size: 26upx;
    color: #888990;
  }
}

.devices {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  color: #1d256e;
  font-size: 33upx;
  // padding: 0;

  .dd {
    padding: 8rpx 10rpx;
    border-radius: 10rpx;
  }

  .colorL {
    color: #1ca9ff;
    margin-left: 20upx;
  }
  .colorH {
    color: #888990;
    margin-left: 20upx;
  }
  .colorX {
    margin-left: 20upx;
    color: #0bd5e7;
  }
}

.task {
  margin-top: 20upx;
  width: 100%;
  padding: 0 16upx;
  .task-1 {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5upx;
    .id {
      color: #1ca9ff;
      font-size: 27upx;
    }
    .img {
      width: 24upx;
      height: 24upx;
      margin-right: 10upx;
    }
    .state0 {
      color: #888990;
      font-size: 23upx;
    }
    .state1 {
      color: #0cd66b;
      font-size: 23upx;
    }
    .bg1 {
      background: rgba(12, 214, 107, 0.1);
      padding: 5upx 10upx;
      border-radius: 10upx;
    }
    .bg0 {
      background: rgba(136, 137, 144, 0.1);
      padding: 5upx 10upx;
      border-radius: 10upx;
    }
    .nums {
      font-size: 27upx;
    }
    .finish {
      color: #888990;
    }
    .gang {
      padding: 0 10upx;
    }
    .all {
      color: #0bd5e7;
    }
    .fin {
      color: #0cd66b;
    }
  }
  .task-2 {
    font-size: 32upx;
    color: #1d256e;
    border-bottom: 1px solid #f1f1f1;
    padding-bottom: 10upx;
  }
  .task-3 {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    font-size: 26upx;
    color: #888990;
    margin-top: 20upx;
    .img {
      width: 22upx;
      height: 26upx;
      margin-right: 10upx;
    }
    .img2 {
      width: 26upx;
      height: 26upx;
      margin-right: 10upx;
    }
    .address {
      max-width: 55%;
      display: flex;
      align-items: center;
    }

    .time {
      max-width: 45%;
      display: flex;
      align-items: center;
    }
  }
  .isClick {
    box-shadow: 0 0 5px 0 rgba(28, 169, 255, 1);
  }
}
.selectclcik {
  background: #1d256e;
  color: #fff;
  .colorL,
  .colorX,
  .colorH {
    color: #fff;
  }
}
.singleList {
  content-visibility: auto;
}
</style>
